// 人脸管理功能

// 删除功能相关变量
let currentDeleteFilename = '';

// 加载人脸列表
function loadFaceList() {
    const originalText = showLoading('allFaceBtn');
    
    $.ajax({
        url: '/list_faces',
        type: 'GET',
        dataType: 'json',
         success: function(response) {
            const faceGrid = $('#faceGrid');
            faceGrid.empty();
            
            if (response.length === 0) {
                faceGrid.html(`
                    <div class="empty-state" style="grid-column: 1/-1;">
                        <i class="fas fa-users"></i>
                        <h3>暂无已入库的人脸</h3>
                        <p>请先上传一些人脸图片到系统中</p>
                    </div>
                `);
            } else {
                response.forEach(function(imageInfo) {
                    const faceItem = $(`
                        <div class="face-item">
                            <button class="face-delete-btn" onclick="showDeleteConfirm('${imageInfo.filename}', event)">
                                <i class="fas fa-trash"></i>
                            </button>
                            <div class="face-content" onclick="showImageModal('${imageInfo.url}', '${imageInfo.filename}')">
                                <img src="${imageInfo.url}" alt="${imageInfo.filename}">
                                <div class="face-name">${imageInfo.filename}</div>
                            </div>
                        </div>
                    `);
                    faceGrid.append(faceItem);
                });
            }
            
            // 更新统计
            $('#totalFaces').text(response.length);
        },
        error: function(error) {
            console.error('Error fetching face images:', error);
            $('#faceGrid').html(`
                <div class="empty-state" style="grid-column: 1/-1;">
                    <i class="fas fa-exclamation-triangle"></i>
                    <h3>加载失败</h3>
                    <p>无法加载人脸列表，请重试</p>
                </div>
            `);
        },
        complete: function() {
            restoreButton('allFaceBtn', originalText);
        }
    });
}

// 显示删除确认对话框
function showDeleteConfirm(filename, event) {
    event.stopPropagation(); // 阻止事件冒泡
    
    currentDeleteFilename = filename;
    $('#deleteFileName').text(filename);
    
    // 显示确认对话框
    const modal = $('#deleteConfirmModal');
    modal.fadeIn(300);
    
    // 聚焦到取消按钮
    setTimeout(() => {
        modal.find('.btn-outline').focus();
    }, 350);
}

// 关闭删除确认对话框
function closeDeleteModal() {
    const modal = $('#deleteConfirmModal');
    modal.fadeOut(300);
    
    // 清理状态
    setTimeout(() => {
        currentDeleteFilename = '';
        $('#deleteFileName').text('');
    }, 300);
}

// 确认删除
function confirmDelete() {
    if (!currentDeleteFilename) {
        return;
    }
    
    const deleteBtn = $('#deleteConfirmModal .btn-danger');
    const originalText = deleteBtn.html();
    deleteBtn.html('<span class="loading"></span> 删除中...');
    deleteBtn.prop('disabled', true);
    
    $.ajax({
        url: '/delete_face',
        type: 'DELETE',
        contentType: 'application/json',
        data: JSON.stringify({
            filename: currentDeleteFilename
        }),
        success: function(response) {
            // 显示成功提示
            showSuccessToast(response.message);
            closeDeleteModal();
            loadFaceList(); // 重新加载人脸列表
            updateStats(); // 更新统计信息
        },
        error: function(xhr) {
            const errorMsg = xhr.responseJSON ? xhr.responseJSON.error : '删除失败，请重试';
            showResult('uploadResult', '删除失败: ' + errorMsg, false);
        },
        complete: function() {
            deleteBtn.html(originalText);
            deleteBtn.prop('disabled', false);
        }
    });
}

// 模态框管理
function showImageModal(imageUrl, filename) {
    const modalImage = $('#modalImage');
    const modal = $('#imageModal');
    
    // 显示模态框
    modal.fadeIn();
    
    // 添加加载状态
    modalImage.addClass('loading').removeClass('loaded');
    
    // 设置图片源
    modalImage.attr('src', imageUrl);
    
    // 图片加载完成
    modalImage.on('load', function() {
        modalImage.removeClass('loading').addClass('loaded');
        
        // 更新标题显示文件名
        $('.modal-title').text('人脸详情 - ' + filename);
    });
    
    // 图片加载失败
    modalImage.on('error', function() {
        modalImage.removeClass('loading');
        modalImage.attr('src', '');
        $('.modal-title').text('图片加载失败');
    });
}

function closeModal() {
    const modalImage = $('#modalImage');
    const modal = $('#imageModal');
    
    // 清理事件监听器
    modalImage.off('load error');
    
    // 重置图片状态
    modalImage.removeClass('loading loaded');
    
    // 隐藏模态框
    modal.fadeOut();
    
    // 重置标题
    $('.modal-title').text('人脸详情');
} 